package com.lin.filter;

import javax.servlet.*;
import java.io.IOException;

public class CharacterEncodingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CharacterEncodingFilter init--");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        // 放行, 继续执行后续过滤器或者目标资源
        System.out.println("execute before~~");
        try {
            chain.doFilter(request, response); // 调用后续过滤器或目标资源
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常堆栈信息
            throw e; // 重新抛出异常，以便进一步处理
        }
        System.out.println("execute after~~");
    }

    @Override
    public void destroy() {
        System.out.println("CharacterEncodingFilter destroy--");
    }
}
